﻿using MediatR;
using PublicCommon;
using T_Rbac.Read.APi.Application.Command.Dapartments;
using T_Rbac_Demain;
using T_Rbac_Rep.Interface;

namespace T_Rbac.Read.APi.Application.Handlers.DapartmentHandlers
{
    public class DepartmentSearchCommandHandler : IRequestHandler<DepartmentSearchCommand, PageResult<Dapartment>>
    {
        private readonly IDapartment dapartment;

        public DepartmentSearchCommandHandler(IDapartment dapartment)
        {
            this.dapartment = dapartment;
        }

        public async Task<PageResult<Dapartment>> Handle(DepartmentSearchCommand request, CancellationToken cancellationToken)
        {
            var list = await dapartment.GetvaluesByResult(x => x.IsDel.Equals(false));
            if (!string.IsNullOrEmpty(request.dname))
            {
                list = list.Where(x => x.Dname.Contains(request.dname));
            }
            if (request.did>0)
            {
                list = list.Where(x => x.Did == request.did);
            }
            int Listcount = list.Count();
            int Pagecount = (int)Math.Ceiling(list.Count() * 1.0 / request.pagesize);
            list = list.OrderByDescending(x => x.Did).Skip((request.pageindex - 1) * request.pagesize).Take(request.pagesize);
            return await Task.FromResult(new PageResult<Dapartment>
            {
                List = list.ToList(),
                PageCount = Pagecount,
                TotalCount = Listcount
            });
        }
    }
}
